<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/10/10
 * Time: 17:26
 */

namespace App\Services;

use App\Models\Permission;

class PermissionService extends BaseService
{
    protected $modelClass = Permission::class;

    /**
     * 添加
     * @param $postData
     * @return bool|string
     * @throws \Exception
     */
    public function add($postData)
    {
        $postData['name'] = $postData['access'];
        if ($postData['pid']) {
            $parentObj = $this->findById($postData['pid'], ['name'], true);
            $postData['name'] = $parentObj->name.'.'.$postData['access'];
        }

        $postData['uuid'] = uuid();

        return $this->saveData($postData);
    }

    /**
     * 编辑权限
     * @param $uuid
     * @param $postData
     * @return mixed
     * @throws \Exception
     */
    public function edit($uuid, $postData)
    {
        $postData['name'] = $postData['access'];

        $obj = $this->findByUuidOrFail($uuid);
        if ($obj->pid) {
            $parentObj = $this->findById($obj->pid, ['name']);
            $postData['name'] = $parentObj->name.'.'.$postData['access'];
        }

        $hasArr = $this->model
            ->where('name', $postData['name'])
            ->pluck('uuid')
            ->diff([$uuid])
            ->count();
        if ($hasArr) {
            throw new \Exception('权限 已存在');
        }

        return $obj->update(filter_null($postData));
    }

    /**
     * 删除
     * @param $uuid
     * @return mixed
     * @throws \Exception
     */
    public function remove($uuid)
    {
        $obj = $this->detail($uuid);
        if (!count($obj->children)) {
            throw new \Exception('此权限下有子权限，禁止删除！');
        }

        if (!$obj->update(['is_enable' => 0])) {
            throw new \Exception('删除失败！');
        }

        return true;
    }

    /**
     * 获取权限详情
     * @param $uuid
     * @return mixed
     * @throws \Exception
     */
    public function detail($uuid)
    {
        return $this->model()->where('uuid', $uuid)->with('children')->first();
    }

    /**
     * 树形菜单
     * @param array $search
     * @param int $per_page
     * @return array
     */
    public function getList($search=[], $per_page=20)
    {
        $model = $this->searcher($this->model, $search)->where('pid', 0)->with('children');

        $columns = $this->model->columns ?? ['*'];

        $conf = [
            'title' => '权限列表',
            'search' => 'conf_search.permission_getList',
            'columns' => 'conf_columns.permission_getList',
            'buttons' => 'conf_buttons.permission_getList'
        ];
        return $this->get_paginate($model->paginate($per_page, $columns), $conf);
    }

}